
local base64 = require 'util.base64'
local json = require "util.json"
local japi = require 'jass.japi'
local jass = require 'jass.common'
local dbg  = require 'jass.debug'

--云消息同步
local trigger1 = jass.CreateTrigger()
local trigger2 = jass.CreateTrigger()
dbg.handle_ref(trigger1)
dbg.handle_ref(trigger2)
japi.DzTriggerRegisterSyncData(trigger1,'cloudToWar3',true)
japi.DzTriggerRegisterSyncData(trigger2,'cloudToWar3_page',true)

local function playerSyncCloud(player,message)
    
    if package.local_test then
        print(message)
    end
    if json.is_json(message) then
        local data = json.decode(message)
        local name = data.name
        local params = data.params or {}
        if name then
            local ename = ('云消息-%s'):format(name)
            player:notify(ename,player,table.unpack(params))
            player:notify('玩家-刷新UI',player)
        end
    end
end


jass.TriggerAddAction(trigger1, function()
    local message = japi.DzGetTriggerSyncData()
    local handle = japi.DzGetTriggerSyncPlayer()
    local player = ac.player[handle]
    playerSyncCloud(player,message)
end)

--云消息 长数据分页同步
jass.TriggerAddAction(trigger2, function()
    local message = japi.DzGetTriggerSyncData()
    local handle = japi.DzGetTriggerSyncPlayer()
    local player = ac.player[handle]
    if json.is_json(message) then
        local data = json.decode(message)
        local time = data.time
        local name = data.name
        local info = data.info
        local page = data.page
        local max = data.page_max
        if time and name and info and page and max then
            if not player._cloud_page then
                player._cloud_page = {}
            end
            local cloud_data = player._cloud_page[name]
            if not cloud_data or cloud_data.time ~=time then
                cloud_data = {}
                cloud_data.time = time
                player._cloud_page[name] = cloud_data
            end
            cloud_data[page] = info[1]
            if #cloud_data==max then
                local real_info = table.concat(cloud_data)
                playerSyncCloud(player,real_info)
            end
        end
    else
        print('无效类型',message)
    end
end)


--发送云消息（每次内容长度不要超过500）
function ac.player.__index:send_cloud(eventName,...)
    local data = {
        name = eventName,
        params = {...},
    }
    local payload = json.encode(data)
    japi.RequestExtraBooleanData(1009, self.handle, 'war3ToCloud', payload, false, 0, 0, 0)
end

